package com.eurobcoin.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class ValidationServlet extends HttpServlet {

	private static final long serialVersionUID = -1298982767533449667L;
	
	private static final Logger logger = LoggerFactory.getLogger(ValidationServlet.class);
	
	private Document document;
	
	private Map<String, Page> pages;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HttpSession session = request.getSession();
//		DesktopModel desktopModel = (DesktopModel)session.getAttribute(SessionKeys.DESKTOP_MODEL);
		
		String pageId = request.getParameter("p");
		
		Page page = this.pages.get(pageId);
		
		String js = "";
		
//		if(page != null) {
//			js = page.toJSONString(desktopModel);
//		}
		
		response.setHeader("Content-Type", "application/javascript");
		response.setCharacterEncoding("UTF-8");
		
		OutputStream os = response.getOutputStream();
		os.write(js.getBytes());
		os.flush();
	}
	
	private void parseDocument() throws Exception {
		
		this.pages = new HashMap<String, Page>();
		
		DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("validation.xml");
		
		this.document = documentBuilder.parse(inputStream);
		
		inputStream.close();
		
		Element root = document.getDocumentElement();
		
		NodeList pages = root.getElementsByTagName("page");
		
		for(int i = 0; i < pages.getLength(); i++) {
			Element page = (Element)pages.item(i);
			String pageId = page.getAttribute("id");
			
			Page oPage = new Page();
			oPage.setId(pageId);
			
			this.pages.put(pageId, oPage);
			
			NodeList elems = page.getElementsByTagName("element");
			
			for(int j = 0; j < elems.getLength(); j++) {
				Element elem = (Element)elems.item(j);
				String elementId = elem.getAttribute("value");
				
				ValidationElement oElem = new ValidationElement();
				oElem.setHtmlElement(elementId);
				
				oPage.getValidationElements().add(oElem);
				
				NodeList attributes = elem.getElementsByTagName("attribute");
				
				for(int k = 0; k < attributes.getLength(); k++) {
					Element attr = (Element)attributes.item(k);
					
					String name = attr.getAttribute("name");
					String value = attr.getAttribute("value");
					
					oElem.getAttributes().put(name, value);
				}
			}
			
		}
	}
	
	public void init() throws ServletException {
		super.init();
		
		try {
			this.parseDocument();
		}catch(Exception e){
			logger.error("An error occured", e);
			throw new ServletException(e);
		}
	}

	private class Page {
		
		private String id;
		
		private List<ValidationElement> validationElements = new ArrayList<ValidationElement>();
		
		public List<ValidationElement> getValidationElements() {
			return this.validationElements;
		}
		
		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}
		
//		public String toJSONString(DesktopModel desktopModel) {
//			StringBuilder sb = new StringBuilder();
//			
//			for(ValidationElement validationElement : this.validationElements) {
//				sb.append(validationElement.toJSONString(desktopModel));
//			}
//			
//			String veStrings = sb.toString();
//			if(veStrings.lastIndexOf(",") == veStrings.length() - 1) {
//				veStrings = veStrings.substring(0, veStrings.length() - 1);
//			}
//			
//			StringBuilder ret = new StringBuilder();
//			
//			ret.append("var validation = [");
//			
//			ret.append(veStrings);
//			
//			ret.append("];");
//			
//			return ret.toString();
//		}
		
	}
	
	private class ValidationElement {
		private String htmlElement;
		
		private Map<String, String> attributes = new HashMap<String, String>();
		
		public Map<String, String> getAttributes() {
			return this.attributes;
		}
		
		public void setHtmlElement(String htmlElement) {
			this.htmlElement = htmlElement;
		}
		
		public String getHtmlElement() {
			return this.htmlElement;
		}
		
//		public String toJSONString(DesktopModel desktopModel) {
//			StringBuilder ret = new StringBuilder();
//			
//			ret.append("{elem: ");
//			ret.append("\"");
//			ret.append(this.htmlElement);
//			ret.append("\"");
//			ret.append(", ");
//			ret.append("values: [");
//			
//			Set<String> keys = this.attributes.keySet();
//			Iterator<String> iKeys = keys.iterator();
//			
//			StringBuilder sb = new StringBuilder();
//			while(iKeys.hasNext()) {
//				String key = iKeys.next();
//				String value = this.attributes.get(key);
//				
//				if("msg".equals(key)) {
//					value = desktopModel.getMessage(value);
//				}
//				
//				sb.append("[");
//				sb.append("\"");
//				sb.append(key);
//				sb.append("\"");
//				sb.append(",");
//				sb.append("\"");
//				sb.append(value);
//				sb.append("\"");
//				sb.append("],");
//			}
//			String valuesList = sb.toString();
//			if(valuesList.lastIndexOf(",") == valuesList.length() - 1) {
//				valuesList = valuesList.substring(0, valuesList.length() - 1);
//			}
//			
//			ret.append(valuesList);
//			
//			ret.append("]},");
//			
//			return ret.toString();
//		}
	}
	
}
